package main

import (
	"fmt"
	"gitee.com/JohnsonSmile/microshop/user/common"
	"gitee.com/JohnsonSmile/microshop/user/domain/repository"
	"gitee.com/JohnsonSmile/microshop/user/domain/service"
	"gitee.com/JohnsonSmile/microshop/user/handler"
	user "gitee.com/JohnsonSmile/microshop/user/proto"
	"github.com/jinzhu/gorm"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/logger"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-plugins/registry/consul/v2"
	ratelimit "github.com/micro/go-plugins/wrapper/ratelimiter/uber/v2"
	opentracing2 "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
	"github.com/opentracing/opentracing-go"
)

var QPS = 100

func main() {
	// 配置中心
	conf, err := common.GetConsulConfig("47.112.13.65", 8500, "/micro/config")
	if err != nil {
		logger.Error(err)
	}
	// 注册中心
	reg := consul.NewRegistry(
		registry.Addrs("47.112.13.65:8500"),
	)

	// 链路追踪
	tracer, closer, err := common.NewTracer("go.micro.service.user", "47.112.13.65:6831")
	if err != nil {
		logger.Fatal(err)
	}
	defer closer.Close()
	opentracing.SetGlobalTracer(tracer)

	// 创建服务
	srv := micro.NewService(
		micro.Name("go.micro.service.user"),
		micro.Version("latest"),
		micro.Registry(reg),
		micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
		micro.WrapHandler(ratelimit.NewHandlerWrapper(QPS)),
	)
	// 创建数据库
	mysqlConf, err := common.GetMysqlConfigFromConsul(conf, "mysql")
	if err != nil {
		logger.Fatal(err)
	}
	mysqlArgs := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true&loc=Local",
		mysqlConf.User,
		mysqlConf.Pwd,
		mysqlConf.Host,
		mysqlConf.Port,
		mysqlConf.Database,
	)
	db, err := gorm.Open("mysql", mysqlArgs)
	if err != nil {
		logger.Error(err)
	}
	defer db.Close()
	db.SingularTable(true)
	// 创建repository
	userRepository := repository.NewUserRepository(db)
	//err = userRepository.InitTable()
	//if err != nil {
	//	logger.Error(err)
	//}
	// 创建service
	dataService := service.NewUserDataService(userRepository)

	srv.Init()

	// Register handler
	err = user.RegisterUserHandler(srv.Server(), &handler.UserHandler{dataService})
	if err != nil {
		logger.Error(err)
	}

	// Run service
	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}
